// 交通信息爬虫
//云开发神坑，必须把异步变为同步，否则return时自动干掉没完的异步。
// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const suffererTravel = db.collection("suffererTravel");
const myTravel = db.collection("myTravel");

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  var time = getDate();


  console.log(time+" data  spider begin")
  var request = require("request");
  let res = await new Promise(function (resolve, reject) {
    request("http://2019ncov.nosugartech.com/data.json", function (error, res, body) {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
  var data = JSON.parse(res)["data"];
  var n = 0;
  for(var i =0,len=data.length;i<len;i++ ){
    // 1 飞机 2 火车 3 地铁 4 长途客车、大巴 5 公交车 6 出租车 7 轮船
    //不记录其他公共场所，这个我们自己标注
    if (data[i]["t_type"] != 8 && data[i]["updated_at"] > time && data[i]["verified"]==1) {
      try{
          await suffererTravel.doc(data[i]["id"]).set({
            data: {
              t_date: data[i]["t_date"],
              t_start: data[i]["t_start"],
              t_end: data[i]["t_end"],
              t_type: data[i]["t_type"],
              t_no: data[i]["t_no"],
              t_pos_start: data[i]["t_pos_start"],
              t_pos_end: data[i]["t_pos_end"],
              who: data[i]["who"],
              source: data[i]["source"],
              updated_at: data[i]["updated_at"]
            }
          })
      }catch(e){
          console.error(e)
      }
      n++;
      
      try {
        await myTravel.where({
          number:data[i]["t_no"],
          date:data[i]["t_date"],
        }).update({
          data:{
            dangerous:true,
            send:true,
            sufferer:data[i]["id"]
          }
        });
      }catch(e){
        console.error(e)
    }

    }

  }  
  console.log(n+" tody new data");
  
  return {
    success:true
  }
}

//云函数的时区比我们慢8小时
function getDate() {
  var nowdate = new Date();
  var y = nowdate.getFullYear();
  var m = nowdate.getMonth() + 1;
  if (m.toString().length == 1) {
    m = "0" + m;
  }
  var d = nowdate.getDate();
  if (d.toString().length == 1) {
    d = "0" + d;
  }
  var to = y + '/' + m + '/' + d;
  return to;
}